# 后端流式接口测试脚本
# 用途：测试后端 /api/v1/game/adventure/stream 接口

$BACKEND_URL = "http://localhost:8080/api/v1/game/adventure/stream"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "测试后端流式历练接口" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan

# 测试场景1：首次历练
Write-Host "场景1：首次历练（无 conversation_id）" -ForegroundColor Yellow
Write-Host "----------------------------------------`n" -ForegroundColor Gray

# 构造用户上下文数据
$userContext = @{
    user_id = 1
    realm = "练气期"
    realm_level = "后期"
    talent = 70
    comprehension = 80
    luck = 70
    adventure_count = 3
    equipments = @(
        @{ id = 201; name = "青铜剑"; type = "武器"; effect = "攻击+10" },
        @{ id = 202; name = "护身符"; type = "防具"; effect = "防御+5" }
    )
    items = @(
        @{ id = 301; name = "火球符"; type = "符箓"; desc = "释放火球"; effect = "伤害30" }
    )
}

# 将用户上下文转换为 JSON 字符串（作为 content）
$userContextJson = $userContext | ConvertTo-Json -Depth 10 -Compress

$requestBody1 = @{
    user_id = "1"
    additional_messages = @(
        @{
            role = "user"
            type = "question"
            content = $userContextJson
            content_type = "text"
        }
    )
    parameters = @{}
} | ConvertTo-Json -Depth 10

Write-Host "请求URL: $BACKEND_URL" -ForegroundColor White
Write-Host "请求体:" -ForegroundColor White
Write-Host $requestBody1 -ForegroundColor Gray
Write-Host "`n发送请求..." -ForegroundColor Green

try {
    # 发送POST请求
    $response = Invoke-WebRequest -Uri $BACKEND_URL -Method Post `
        -Headers @{ "Content-Type" = "application/json" } `
        -Body $requestBody1 `
        -TimeoutSec 60
    
    Write-Host "`n✅ 响应状态: $($response.StatusCode)" -ForegroundColor Green
    Write-Host "`n流式响应内容:" -ForegroundColor Yellow
    Write-Host "========================================" -ForegroundColor Gray
    
    # 解析 SSE 响应
    $lines = $response.Content -split "`n"
    $conversationId = ""
    
    foreach ($line in $lines) {
        $line = $line.Trim()
        if ($line -eq "") { continue }
        
        if ($line.StartsWith("event:")) {
            Write-Host $line -ForegroundColor Magenta
        }
        elseif ($line.StartsWith("data:")) {
            Write-Host $line -ForegroundColor Cyan
            
            # 尝试解析 JSON
            $jsonData = $line.Substring(5).Trim()
            try {
                $obj = $jsonData | ConvertFrom-Json
                
                if ($obj.conversation_id) {
                    $conversationId = $obj.conversation_id
                    Write-Host "  📌 conversation_id: $conversationId" -ForegroundColor Yellow
                }
                
                if ($obj.message -and $obj.message.content) {
                    Write-Host "  💬 内容: $($obj.message.content)" -ForegroundColor White
                }
            }
            catch {
                Write-Host "  ⚠️ JSON 解析失败" -ForegroundColor Red
            }
        }
        else {
            Write-Host $line -ForegroundColor Gray
        }
    }
    
    Write-Host "`n========================================" -ForegroundColor Gray
    
    if ($conversationId) {
        Write-Host "`n✅ 获取到 conversation_id: $conversationId" -ForegroundColor Green
        
        # 提示进行第二次测试
        Write-Host "`n是否测试场景2（用户做出选择）？[Y/N]" -ForegroundColor Yellow
        $continue = Read-Host
        
        if ($continue -eq "Y" -or $continue -eq "y") {
            Write-Host "`n场景2：用户做出选择（带 conversation_id）" -ForegroundColor Yellow
            Write-Host "----------------------------------------`n" -ForegroundColor Gray
            
            # 构造用户选择的上下文
            $userChoiceContext = @{
                user_choice = 1
                user_context = $userContext
                history = @()
            }
            
            $userChoiceJson = $userChoiceContext | ConvertTo-Json -Depth 10 -Compress
            
            $requestBody2 = @{
                user_id = "1"
                conversation_id = $conversationId
                additional_messages = @(
                    @{
                        role = "user"
                        type = "question"
                        content = $userChoiceJson
                        content_type = "text"
                    }
                )
                parameters = @{}
            } | ConvertTo-Json -Depth 10
            
            Write-Host "请求URL: $BACKEND_URL" -ForegroundColor White
            Write-Host "请求体:" -ForegroundColor White
            Write-Host $requestBody2 -ForegroundColor Gray
            Write-Host "`n发送请求..." -ForegroundColor Green
            
            $response2 = Invoke-WebRequest -Uri $BACKEND_URL -Method Post `
                -Headers @{ "Content-Type" = "application/json" } `
                -Body $requestBody2 `
                -TimeoutSec 60
            
            Write-Host "`n✅ 响应状态: $($response2.StatusCode)" -ForegroundColor Green
            Write-Host "`n流式响应内容:" -ForegroundColor Yellow
            Write-Host "========================================" -ForegroundColor Gray
            
            $lines2 = $response2.Content -split "`n"
            foreach ($line in $lines2) {
                $line = $line.Trim()
                if ($line -eq "") { continue }
                
                if ($line.StartsWith("event:")) {
                    Write-Host $line -ForegroundColor Magenta
                }
                elseif ($line.StartsWith("data:")) {
                    Write-Host $line -ForegroundColor Cyan
                    
                    $jsonData = $line.Substring(5).Trim()
                    try {
                        $obj = $jsonData | ConvertFrom-Json
                        if ($obj.message -and $obj.message.content) {
                            Write-Host "  💬 内容: $($obj.message.content)" -ForegroundColor White
                        }
                    }
                    catch {}
                }
                else {
                    Write-Host $line -ForegroundColor Gray
                }
            }
            
            Write-Host "`n========================================" -ForegroundColor Gray
        }
    }
}
catch {
    Write-Host "`n❌ 请求失败:" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    
    # 尝试读取错误响应
    if ($_.ErrorDetails) {
        Write-Host "`n错误详情:" -ForegroundColor Red
        Write-Host $_.ErrorDetails.Message -ForegroundColor Gray
    }
}

Write-Host "`n测试完成！" -ForegroundColor Green
